
var net = require('net');
//var actorify = require('./lib/roleactor.js');
var async = require('async');

var StackServer = require('./lib/stackserver.js');
var StackClient = require('./lib/stackclient.js');

var MODNAME = 'TcpCore';

var stacks = new (function Stacks() {
  /**
   * stacks can either be a server or a client
   */
  this._server = null,
  this._client = null;
  this.logger = null;
  this._modname = null;
  
  /**
   * is invoked to supply any args
   */
  this.onInit = function onInit (pParentObj) {
	  MODNAME = this._modname = pParentObj._Config.NAME + '_' + MODNAME;
	  this.logger = pParentObj.logger;  
  };
 
  /**
   * create a stacks server to listen for client connections
   *
   * @api public
   * @param <Number> port
   * @param <Function> callback
   */
  this.listen = function listen(obj, onStartedListcallback, onNewConCallback) {   
    this.logger.log(MODNAME, 'INFO_LEVEL_4', 'listen() is called.');

    if (this._server) {      
      this.logger.log(MODNAME, 'WARNING', 'listen() has already been called on this instance.');
    }
    
    this._server = new StackServer(this);
    this._server.listen(obj, onStartedListcallback, onNewConCallback);
  };

  /**
   * make a request to stacks
   * 
   * @api public
   * @param <String> type
   * @param <Mixed> body
   * @param <Object> options
   * @param <Function> callback
   */
  this.request = function request(type, body, options, callback) {
	  this.logger.log(MODNAME, 'INFO_LEVEL_4', 'request() is called.');

    if (this._server) {
      this._server.request(type, body, options, callback);
    } else {
    	this.logger.log(MODNAME, 'WARNING', 'This instance is not a server, and cannot make requests');
    }
  };
  /**
   * removes the client object
   */
  this.removeClient = function removeClient () {
	  delete this._client;
	  this.logger.log(MODNAME, 'INFO_LEVEL_4', 'Removed Client object');
  };
  /**
   * create a stacks client to connect to a stacks server
   * 
   * @api public
   * @param <Mixed> server
   * @param <Function> callback
   */
  this.connect = function connect(server, callback) {
	  this.logger.log(MODNAME, 'INFO_LEVEL_4', 'connect() is called.');

    if (this._client) {
    	if (this._client._isConnected) {
    		this.logger.log(MODNAME, 'WARNING', 'connect() has already been called on this instance.');    		
    	}
    } else {    
    	this._client = new StackClient(this);
    }
    this._client.connect(server, callback);
    this.disconnect = this._client.disconnect;
  };

  return this;
});

/**
 * export api
 */
module.exports = stacks;


